/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Robin Chutaux
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package custom.base.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatTextView;

import custom.base.R;
import custom.base.utils.TxtUtil;


/**
 * RippleView custom layout
 * <p/>
 * Custom Layout that allows to use Ripple UI pattern above API 21
 *
 * @author luozisong
 * @version 2016.0303
 */
public class LoadLayout extends LinearLayout {

    public LoadLayout(Context context) {
        super(context);
    }

    public LoadLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public LoadLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private View view;
    private ImageView img;
    private TextView tvName;
    private AppCompatTextView tvReload;

    /**
     * 是否已经加载过,已经加载过的不会再重置页面
     */
    private boolean isLoaded = false;
    /**
     * 无论什么情况下切换到状态加载中时都会展示加载界面,false只会展示一次
     */
    private boolean showLoadAnytime = false;
    private String TXT_FAIL = "无网络或网络出错", TXT_EMPTY = "暂无数据", TXT_LOADING = "加载中", TXT_RELOAD = "重新加载";
    /**
     * 状态 0:初始隐藏状态 1：加载成功状态 2：加载失败状态 3：加载成功但数据为空
     */
    private int type = 0;
    /**
     * 初始隐藏状态
     */
    public static final int TYPE_INIT = 0;
    /**
     * 加载成功状态
     */
    public static final int TYPE_SUCCESS = 1;
    /**
     * 加载失败状态
     */
    public static final int TYPE_ERROR = 2;
    /**
     * 加载成功但数据为空
     */
    public static final int TYPE_SUCCESS_EMPTY = 3;
    /**
     * 加载中
     */
    public static final int TYPE_LOADING = 4;
    /**
     * 为空的时候的图标
     */
    int emptyIcon;
    /**
     * 错误的时候的图标
     */
    int errorIcon;
    boolean showIcon = true;//default white

    /**
     * Method that initializes all fields and sets listeners
     *
     * @param context Context used to create this view
     * @param attrs   Attribute used to initialize fields
     */
    private void init(final Context context, final AttributeSet attrs) {

        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LoadLayout);
        String EMPTY = typedArray.getString(R.styleable.LoadLayout_txt_empty);//default white
        String FAIL = typedArray.getString(R.styleable.LoadLayout_txt_error);//default white
        String LOADING = typedArray.getString(R.styleable.LoadLayout_txt_loading);//default white
        String RELOAD = typedArray.getString(R.styleable.LoadLayout_txt_reload);//default white
        showIcon = typedArray.getBoolean(R.styleable.LoadLayout_show_icon, showIcon);
        showLoadAnytime = typedArray.getBoolean(R.styleable.LoadLayout_showLoadAnytime, showLoadAnytime);
        emptyIcon = typedArray.getResourceId(R.styleable.LoadLayout_empty_icon, R.drawable.img_load_empty);//default white
        errorIcon = typedArray.getResourceId(R.styleable.LoadLayout_error_icon, R.drawable.img_load_no_network);//default white
        typedArray.recycle();

        if (!isEmpty(EMPTY))
            TXT_EMPTY = EMPTY;
        if (!isEmpty(FAIL))
            TXT_FAIL = FAIL;
        if (!isEmpty(LOADING))
            TXT_LOADING = LOADING;
        if (!isEmpty(RELOAD))
            TXT_RELOAD = RELOAD;

        setBackgroundColor(Color.WHITE);
        setGravity(Gravity.CENTER);
        setOrientation(VERTICAL);

        view = LayoutInflater.from(context).inflate(R.layout.view_load_layout, this);
        img = (ImageView) view.findViewById(R.id.view_load_layout_img);
        tvName = (TextView) view.findViewById(R.id.view_load_layout_name);
        tvReload = (AppCompatTextView) view.findViewById(R.id.view_load_layout_reload);

        setStatus(TYPE_INIT);
        if (showIcon) {
            img.setVisibility(VISIBLE);
        } else {
            img.setVisibility(GONE);
        }

        setClickable(true);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        setReloadListener();
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * @param type 状态 TYPE_INIT:初始隐藏状态
     *             TYPE_SUCCESS：加载成功状态
     *             TYPE_ERROR：加载失败状态
     *             TYPE_SUCCESS_EMPTY：加载成功但数据为空
     *             TYPE_LOADING：加载中
     */
    public void setStatus(int type) {
        setStatus(type, "");
    }

    /**
     * @param type     状态 TYPE_INIT:初始隐藏状态
     *                 TYPE_SUCCESS：加载成功状态
     *                 TYPE_ERROR：加载失败状态
     *                 TYPE_SUCCESS_EMPTY：加载成功但数据为空
     *                 TYPE_LOADING：加载中
     * @param hintText 提示文本
     */
    public void setStatus(int type, String hintText) {
        switch (type) {
            case TYPE_INIT:
                setVisibility(GONE);
                break;
            case TYPE_SUCCESS:
                setVisibility(GONE);
                isLoaded = true;
                break;
            case TYPE_ERROR:
                setVisibility(VISIBLE);
                tvReload.setVisibility(VISIBLE);
                img.setImageResource(errorIcon);
                if (showIcon) {
                    img.setVisibility(VISIBLE);
                } else {
                    img.setVisibility(GONE);
                }
                if (TxtUtil.isEmpty(hintText))
                    hintText = TXT_FAIL;
                tvName.setText(hintText);
                tvReload.setText(TXT_RELOAD);
                break;
            case TYPE_SUCCESS_EMPTY:
                setVisibility(VISIBLE);
                tvReload.setVisibility(GONE);
                img.setImageResource(emptyIcon);
                if (showIcon) {
                    img.setVisibility(VISIBLE);
                } else {
                    img.setVisibility(GONE);
                }
                if (TxtUtil.isEmpty(hintText))
                    hintText = TXT_EMPTY;
                tvName.setText(hintText);
                break;
            case TYPE_LOADING:
                if (isLoaded && !showLoadAnytime) {
                    setVisibility(GONE);
                } else {
                    setVisibility(VISIBLE);
                    tvReload.setVisibility(GONE);
                    img.setVisibility(GONE);
                    if (TxtUtil.isEmpty(hintText))
                        hintText = TXT_LOADING;
                    tvName.setText(hintText);
                }
                break;
        }
    }

    /**
     * 重新加载点击监听
     */
    public void setReloadListener() {
        tvReload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                setStatus(TYPE_LOADING);
                if (LoadLayout.this.onReloadListener != null)
                    LoadLayout.this.onReloadListener.onReload();
            }
        });
    }


    OnReloadListener onReloadListener = null;

    public void setOnReloadListener(OnReloadListener onReloadListener) {
        this.onReloadListener = onReloadListener;
    }

    public interface OnReloadListener {
        void onReload();
    }

    public static boolean isEmpty(String str) {
        if (str == null)
            return true;
        if (str.equals("") || str.length() == 0 || str.trim().length() == 0) {
            return true;
        }
        return false;
    }
}
